package com.zs.studentmanager.controller;

import com.zs.studentmanager.common.ResponseCodeEnum;
import com.zs.studentmanager.common.Result;
import com.zs.studentmanager.entity.domain.User;
import com.zs.studentmanager.entity.requestParam.LoginParams;
import com.zs.studentmanager.entity.vo.LoginVo;
import com.zs.studentmanager.service.UserService;
import com.zs.studentmanager.utils.CommonUtils;
import com.zs.studentmanager.utils.JwtUtil;
import com.zs.studentmanager.utils.Md5Util;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: 周小白
 * @date: 2024-01-19 20:06
 **/
@RestController
@Tag(name= "登录管理")
public class LoginController {

    private final UserService userService;

    public LoginController(UserService userService) {
        this.userService = userService;
    }


    /**
     * 登录
     * @param loginParams 登录参数
     * @return Result
     */
    @PostMapping("/login")
    @Operation(summary = "登录")
    public Result login(@RequestBody LoginParams loginParams,
                                     HttpServletRequest request) {
        if (loginParams == null) {
            return Result.fail(ResponseCodeEnum.NO_PARAM);
        }

        User user = userService.login(loginParams);
        if (user == null) {
            return Result.fail("登录失败！账号不存在！");
        } else if (!user.getPassword().equals(Md5Util.md5(loginParams.getPassword()))) {
            return Result.fail("登录失败！账号或密码错误！");
        } else if (user.getStatus() == 0) {
            return Result.fail("登录失败！账号已被禁用！");
        }

        String token = JwtUtil.createToken(user);
        request.getServletContext().setAttribute("token", token);
        LoginVo loginUser = new LoginVo();
        loginUser.setToken(token);
        loginUser.setUser(CommonUtils.toBeSafe(user));

        return Result.success(loginUser);
    }


    /**
     * 登出
     * @param request 请求
     * @return Result
     */
    @PostMapping("/logout")
    @Operation(summary = "登出")
    public Result logout(HttpServletRequest request) {
        request.getServletContext().removeAttribute("token");

        return Result.success();
    }
}
